package server.billing;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import model.Bill;
import model.PriceSteps;

/**
 * Class represents the implementation of the secure part of the billing server.
 * It provides all functionality of the billing server. The class shall be hold
 * as a remote reference in the auction server and therefor extends
 * UnicastRemoteObject.
 */
public class BillingServerSecureImpl extends UnicastRemoteObject implements
		BillingServerSecure {

	private static final long serialVersionUID = 732172772989578174L;
	private PriceSteps steps;
	private Map<String, Bill> bills;

	public BillingServerSecureImpl() throws RemoteException {
		super();
		this.steps = new PriceSteps();
		this.bills = Collections
				.synchronizedMap(new ConcurrentHashMap<String, Bill>());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see server.billing.BillingServerSecure#getPriceSteps()
	 */
	@Override
	public PriceSteps getPriceSteps() throws RemoteException {
		return steps;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see server.billing.BillingServerSecure#createPriceStep(double, double,
	 * double, double)
	 */
	@Override
	public void createPriceStep(double startPrice, double endPrice,
			double fixedPrice, double variablePricePercent)
			throws RemoteException {
		try {
			steps.addPriceStep(startPrice, endPrice, fixedPrice,
					variablePricePercent);
		} catch (IllegalArgumentException e) {
			throw new RemoteException(e.getMessage());
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see server.billing.BillingServerSecure#deletePriceStep(double, double)
	 */
	@Override
	public void deletePriceStep(double startPrice, double endPrice)
			throws RemoteException {
		try {
			steps.removePriceStep(startPrice, endPrice);
		} catch (IllegalArgumentException e) {
			throw new RemoteException(e.getMessage());
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see server.billing.BillingServerSecure#billAuction(java.lang.String,
	 * long, double)
	 */
	@Override
	public void billAuction(String user, long auctionID, double price)
			throws RemoteException {

		Bill bill = this.bills.get(user);
		if (bill == null) {
			bill = new Bill(user);
			this.bills.put(user, bill);
		}
		bill.addEntry(auctionID, price, this.steps.getFixedFee(price),
				this.steps.getVariableFee(price));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see server.billing.BillingServerSecure#getBill(java.lang.String)
	 */
	@Override
	public Bill getBill(String user) throws RemoteException {
		return this.bills.get(user);
	}

}
